<template>
  <div class="overlappingList">
    <!-- TODO 没数据的展示，感觉很有问题 -->
    <!-- <div v-if="(echartsRadarData.reference && echartsRadarData.reference.length > 0) || operation !== 'attribution'"> -->
      <div class="trendoverlappingList" v-if="operation === 'attribution'">
      <div class="trendListName">
        <div v-for="(item, index) in attributionHeaderList" :key="index" class="overlappingListHeader">
          <template>
            <div>
              <div class="drillheaderName">{{ item }}</div>
            </div>
          </template>
        </div>
      </div>
      <div class="referenceList">
        <div v-for="(item, index) in referenceList" :key="index" class="indicatorItem">
          <div class="indicatorSonItem">
            <div class="indicatorName">{{ item.name }}</div>
            <div
              class="indicatorValue"
            >
              <div
                :class="
                  item.referenceValue ? item.referenceValue < item.value && 'valueColor' : index < 6 && 'valueColor'
                "
              >
                {{ item.value | dataFormatWidthUnitLevel('pt') }}
              </div>
            </div>
            <div
              class="referenceValue"
              v-if="attributionHeaderList.length > 2"
            >
              <div>{{ !!item.referenceValue ? item.referenceValue  : null | dataFormatWidthUnitLevel('pt') }}</div>
            </div>
          </div>
        </div>
      </div>
      </div>
      <div class="trendoverlappingList" v-if="operation !== 'attribution'">
        <div class="trendListName">
          <div v-for="(item, index) in contentCode" :key="index" :class="item.name ? 'overlappingListHeader' : ''">
            <template>
              <div @click="handleSortToggle(item)">
                <div :class="operation === 'pivot' ? 'pivotHeaderName' : 'drillheaderName'">{{ item.name }}</div>
              </div>

              <div class="sortTble" v-if="item.role !== 'dim'">
                <div class="filterTbleItem">
                  <svg-icon
                    :icon="item.sortUp ? 'iconShengxu' : item.sortDown ? 'iconJianxu' : 'defalutPaixu'"
                  ></svg-icon>
                </div>
              </div>
            </template>
          </div>
        </div>
        <div v-if="operation === 'pivot'">
          <div v-for="(item, listIndex) in afterData" :key="listIndex" class="trendListItem" style="display: flex;">
            <div class="trendItemName" @click="handleFilterItem(item)">
              {{ item.orgBranchName === null ? '' : item.orgBranchName }}
            </div>
            <div class="rightContent">
              <div
                v-for="(code, index) in item.list"
                :key="index"
                @click="handleFilters(code)"
                :class="secondaryType.length > 0 ? 'listItem' : 'listItem secondaryClass'"
              >
                <div v-for="(fieldCode, index) in contentCode.slice(1)" :key="index" class="trendSonItem">
                  <div :class="index === 0 ? 'trendItemrate firstList' : 'trendItemrate'" style="width: 60px">
                    <div
                      :class="[
                        { shangshengColor: fieldCode.isSecondary && code[fieldCode.logicCode] >= 0 },
                        { xiajiangColor: fieldCode.isSecondary && code[fieldCode.logicCode] < 0 },
                        { numberFontSize: fieldCode.role !== 'dim' },
                        { pivotFontSizeType: fieldCode.type === 'primary' }
                      ]"
                    >
                      {{ code[fieldCode.logicCode] | dataFormatWidthUnitLevel(fieldCode.dataType, UnitLevel) }}
                    </div>
                    <div
                      v-if="
                        fieldCode.isSecondary &&
                        code[fieldCode.logicCode] >= 0 &&
                        code[fieldCode.logicCode] !== '' &&
                        code[fieldCode.logicCode] !== null
                      "
                    >
                      <svg-icon icon="shangsheng" class="shangsheng"></svg-icon>
                    </div>
                    <div
                      v-if="
                        fieldCode.isSecondary &&
                        code[fieldCode.logicCode] < 0 &&
                        code[fieldCode.logicCode] !== '' &&
                        code[fieldCode.logicCode] !== null
                      "
                    >
                      <svg-icon icon="xiajiang" class="xiajiang"></svg-icon>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="trendListItem" v-if="operation === 'drill'">
          <div
            v-for="(code, codeIndex) in afterData[0] && afterData[0].list"
            :key="codeIndex"
            @click="handleFilters(code)"
            class="listItem"
          >
            <div v-for="(fieldCode, index) in contentCode" :key="index" class="trendSonItem">
              <div :class="index === 0 ? 'trendItemrate firstList' : 'trendItemrate'" style="width: 90px">
                <div
                  :class="[
                    { trendSonItemColor: codeIndex < 3 && index === 1 },
                    {
                      shangshengColor: fieldCode.isSecondary && code[fieldCode.logicCode] >= 0
                    },
                    {
                      xiajiangColor: fieldCode.isSecondary && code[fieldCode.logicCode] < 0
                    },
                    { numberFontSize: fieldCode.role !== 'dim' },
                    { drillFontSizeType: fieldCode.type === 'primary' }
                  ]"
                >
                  {{
                    code[fieldCode.logicCode] === null
                      ? ''
                      : code[fieldCode.logicCode] | dataFormatWidthUnitLevel(fieldCode.dataType, UnitLevel)
                  }}
                </div>
                <div
                  v-if="
                    fieldCode.isSecondary &&
                    code[fieldCode.logicCode] >= 0 &&
                    code[fieldCode.logicCode] !== '' &&
                    code[fieldCode.logicCode] !== null
                  "
                >
                  <svg-icon icon="shangsheng" class="shangsheng"></svg-icon>
                </div>
                <div
                  v-if="
                    fieldCode.isSecondary &&
                    code[fieldCode.logicCode] < 0 &&
                    code[fieldCode.logicCode] !== '' &&
                    code[fieldCode.logicCode] !== null
                  "
                >
                  <svg-icon icon="xiajiang" class="xiajiang"></svg-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="fixButton">
        <div class="pupButtonBox">
          <van-button
            :plain="false"
            class="pupButton"
            type="default"
            style="margin-right: 10px"
            v-if="operation !== 'drill'"
            @click="handledDrillModifyPopup"
            ><div class="istracked">下钻</div></van-button
          >
          <van-button
            :plain="false"
            class="pupButton"
            type="default"
            style="margin-right: 10px"
            v-if="operation !== 'pivot'"
            @click="handledPivotModifyPopup"
            ><div class="istracked">交叉</div></van-button
          >
          <van-button
            :plain="false"
            style="margin-right: 10px"
            class="pupButton"
            type="default"
            v-if="operation !== 'attribution'"
            @click="handleAttribution"
            ><div class="istracked">归因</div></van-button
          >
        </div>
        <van-button
          :disabled="trackBtnDisabled"
          :plain="false"
          class="trackPupButton"
          @click="handleTrackClick"
          :type="trackBtnDisabled ? 'default' : 'info'"
          ><div class="istracked">{{ tracktext }}</div></van-button
        >
      </div>
    <!-- </div>
    <div class="noListTable" v-else> 无数据~</div> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { saveFeeds } from '@/api/home'
import sensormixin from '@/mixins'
export default {
  mixins: [sensormixin],
  // 列表头部fields, 列表值dataContent, 列表类型operation, 列表的单位，处理值UnitLevel
  props: ['fields', 'dataContent', 'operation', 'UnitLevel', 'queryParams', 'headerNumber', 'filterData', 'trackParame', 'echartsRadarData', 'istracked', 'secondaryNumber'],
  data() {
    return {
      handleFiltersFlag: false,
      trackPupButtonFlag: false,
      trendItem: {}, // 选中的单条数据
      contentCode: [], // 拿到code集合
      contentRefCode: '', // 拿到refCode集合
      tempArr: [], // 暂时存放处理交叉的数据
      afterData: [], // 用来展示列表数据
      secondaryType: [], // 是否有参考系
      attributionHeaderList: [],
      referenceList: [],
      notDataImage: false
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'ticket']),
    tracktext() {
      return this.trackBtnDisabled ? '已追踪' : '追踪'
    },
    trackBtnDisabled() {
      return this.istracked
    }
  },
  methods: {
    // 排序切换，展示高亮
    handleSortToggle(item) {
      if (item.role === 'dim') {
        return
      } else {
        let sortFiledContent = []
        sortFiledContent = this.contentCode.filter(child => {
          if (child.logicCode === item.logicCode) {
            if (child.sortUp === false && child.sortDown === false) {
              child.sortUp = true
            } else {
              child.sortUp = !child.sortUp
              child.sortDown = !child.sortDown
            }
          } else {
            child.sortUp = false
            child.sortDown = false
          }
          return item
        })
        this.$emit('sortList', item.logicCode, sortFiledContent)
      }
    },
    initData() {
      // fields处理
      const dims = this.fields.filter(m => m.role === 'dim')
      for (let index = 0; index < dims.length; index++) {
        const element = dims[index]
        this.contentRefCode = element.refCode
        this.contentCode.push({ ...element })
      }
      const p = this.fields.find(m => m.role === 'measure' && m.type === 'primary')
      this.contentCode.push({ ...p, isPrimary: true })
      const se = this.fields.find(m => m.role === 'measure' && m.type === 'secondary')
      this.contentCode.push({ ...se, isSecondary: true })
      console.log(this.contentCode, 'this.contentCode')
      // 交叉数据处理
      if (this.operation === 'pivot') {
        for (let n = 0; n < this.dataContent.length; n++) {
          const lc = this.contentCode[0].logicCode
          // 维度相同的存放在同一个数组
          if (this.tempArr.indexOf(this.dataContent[n][lc]) === -1) {
            this.afterData.push({
              orgBranchName: this.dataContent[n][lc],
              list: [this.dataContent[n]]
            })
            this.tempArr.push(this.dataContent[n][lc])
          } else {
            for (let j = 0; j < this.afterData.length; j++) {
              if (this.afterData[j].orgBranchName === this.dataContent[n][lc]) {
                this.afterData[j].list.push(this.dataContent[n])
              }
            }
          }
        }
      } else if (this.operation === 'drill') {
        // 下钻不处理
        this.afterData.push({ list: this.dataContent })
      }
      this.contentCode = this.contentCode.filter(item => item.name && item.logicCode)
      this.secondaryType = this.contentCode.filter(item => item.role === 'measure' && item.type === 'secondary')
    },
    // 点击选择
    async handleFilters(item) {
      this.trendItem = item
      this.$emit('getTrendList', true, this.trendItem, this.contentRefCode, this.operation)
    },
    async handleTrackClick() {
      if (this.trackPupButtonFlag) return
      this.trackPupButtonFlag = true
      const params = {
        'snapshotTime': this.queryParams.queryDate,
        'avatorUrl': this.userInfo?.avatar,
        'comparedValue': this.secondaryNumber,
        'indexValue': this.headerNumber + '',
        'summarizingKey': this.queryParams.targetCode,
        'dateType': this.queryParams.dateType,
        'dimensionInfoList': this.filterData.length ? this.filterData : [{ code: 'mkt_org_branch', value: 'all' }]
      }
      const status = ['', null, 'null'].includes(params.indexValue) && ['', null, 'null'].includes(params.comparedValue)
      if (status) {
        this.$toast('该数据不能追踪')
        return
      }
      const data = await saveFeeds(params)
      this.trackPupButtonFlag = false
      if (data.success && ['0', '2'].includes(data.value.addFlag)) {
        // this.istracked = true
        this.$toast('已追踪，请至"我的"页面查看')
        this.$emit('istracked_')
        try {
          // 增加创建追踪埋点
          this.createTraceForSensor()
        } catch (error) {
          console.log('增加创建追踪埋点报错：', error)
        }
      }
    },
    // 归因
    handleAttribution() {
      if (this.queryParams.targetCode === 'rate_13') {
        this.$emit('getAttribution', 'modify')
        try {
          // 归因分析事件名称
          this.attributionToAnalyse()
        } catch (error) {
          console.log('归因分析埋点报错：', error)
        }
      } else {
        this.$toast('目前仅13月继续率指标支持归因分析，欢迎体验。当前指标暂不支持归因分析，欢迎向驾驶舱项目组提供分析思路与建议。')
      }
    },
    handledDrillModifyPopup() {
      this.$emit('modifyPopup', true, 'drill', 'fixButton')
    },
    handledPivotModifyPopup() {
      this.$emit('modifyPopup', true, 'pivot', 'fixButton')
    },
    // 点击选中,交叉维度不可点击
    handleFilterItem(filterItem) {
      if (filterItem.list.length === 1) {
        this.trendItem = filterItem.list[0]
        this.$emit('getTrendList', true, this.trendItem, this.contentRefCode)
      } else {
        return
      }
    }
  },
  watch: {
    dataContent(val) {
      if (this.operation !== 'attribution') {
        this.contentCode = []
        this.afterData = []
        this.tempArr = []
        this.initData()
      }
    },

    echartsRadarData(val) {
      if (val.reference && val.reference.length === 0) {
        return
      }
      this.attributionHeaderList = ['归因指标', '当前值']
      if (val.indicator && val.indicator.length > 0) {
        if (this.attributionHeaderList.length < 3) {
          this.attributionHeaderList.push('参考值')
        }
        val.indicator.map(i => {
          val.reference.map(r => {
            if (i.name === r.name) {
              i.referenceValue = r.value
            }
          })
        })
        this.referenceList = val.indicator
      } else {
        this.referenceList = val.reference
      }
      if (this.filterData.length > 0) {
        this.attributionHeaderList[this.attributionHeaderList.length - 1] = '参考值'
      } else {
        this.attributionHeaderList[this.attributionHeaderList.length - 1] = '当前值'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.van-pull-refresh {
  min-height: calc(100vh - 46px);
}
.overlappingList {
  .trendoverlappingList {
    .trendListName {
      display: flex;
      justify-content: space-between;
      padding-bottom: 11px;
      .overlappingListHeader {
        display: flex;
        align-items: center;
        line-height: 17px;
        font-weight: 400;
        font-size: 12px;
        color: #a3a5ac;
        .drillheaderName {
          width: 73px;
        }
        .pivotHeaderName {
          width: 48px;
        }
        &:nth-last-child(1),
        &:nth-last-child(2) {
          text-align: right;
          justify-content: flex-end;
        }
        &:nth-child(1) {
          text-align: left;
        }
      }
      .sortTble {
        display: flex;
        .filterTbleItem {
          font-size: 16px;
        }
      }
    }
    .trendListItem {
      border-top: 1px dashed #4a505c;
      align-items: center;
      .rightContent {
        width: 100%;
      }
      .trendItemName {
        font-size: 13px;
        width: 70px;
        color: #e9e9ed;
        background: none;
        text-align: left;
        margin: auto 0px;
        margin-right: 26px;
      }
      .listItem {
        display: flex;
        justify-content: space-between;
        padding: 14px 0px;
        border-bottom: 1px dashed #353a45;
        .trendSonItem {
          margin: auto 0px;
          .trendItemrate {
            display: flex;
            justify-content: flex-end;
            font-size: 14px;
            font-weight: 500;
            width: 73px;
            color: #e9e9ed;
            .shangsheng {
              margin-left: 4px;
              width: 16px;
              height: 16px;
            }
            .xiajiang {
              margin-left: 4px;
              width: 16px;
              height: 16px;
            }
            .numberFontSize {
              font-size: 16px;
            }
            .pivotFontSizeType {
              padding-right: 20px;
            }
            .drillFontSizeType {
              padding-right: 16px;
            }
          }
          .firstList {
            display: inherit;
            margin: auto;
          }
          .trendSonItemColor {
            color: #ffb440;
          }

          &:nth-child(1) {
            display: inline-block;
            margin: none;
          }
          &:nth-last-child(1) {
            display: inline-block;
          }
        }
        &:nth-last-child(1) {
          border-bottom: none;
        }
      }
      .secondaryClass {
        padding-left: 60px;
      }
    }
  }
  .xiajiangColor {
    color: #6ed2bb;
  }
  .shangshengColor {
    color: rgba(253, 128, 141, 1);
  }
  .referenceList {
    border-top: 1px dashed #353a45;
    .indicatorItem {
      padding: 14px 0px;
      border-bottom: 1px dashed #353a45;
      .indicatorSonItem {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        font-weight: 500;
        color: #e9e9ed;
        .indicatorName {
          width: 100px;
        }
        .valueColor {
          color: #ffb440;
        }
        .indicatorValue {
          display: flex;
          width: 50px;
          justify-content: flex-end;
        }
        .referenceValue {
          display: flex;
          width: 73px;
          justify-content: flex-end;
        }
      }
    }
  }
  .fixButton {
    position: fixed;
    bottom: -7px;
    left: 0px;
    display: flex;
    justify-content: space-between;
    height: 94px;
    background: #393f52;
    width: 100%;
    padding: 16px 20px 0px 20px;
    border-radius: 20px 20px 0px 0px;
    .pupButtonBox {
      display: flex;
      .pupButton {
        width: 60px;
        .istracked {
          width: 50px;
        }
      }
    }
    .trackPupButton {
      width: 183px;
    }
  }
}
 .noListTable {
    text-align: center;
    font-size: 14px;
    margin-top: 10px;
    color: rgba(255, 255, 255, 0.5);
  }
// .noData-container {
//   width: 375px;
//   .noData {
//     width: 180px;
//     height: 167px;
//     margin: 175px auto 0px;
//     display: block;
//   }
//   .noDataMessage {
//     text-align: center;
//     font-weight: 400;
//     color: rgba(233, 233, 237, 0.64);
//     line-height: 20px;
//     font-size: 14px;
//     padding-top: 5px;
//   }
// }
</style>
